const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.default')
const { tokenExpiredError, jsonWebTokenError, hasNotAdminPermission } = require('../consisitant/err.type')

const auth = async (ctx, next) => {
    const { authorization } = ctx.request.header
    try {
        const user = jwt.verify(authorization, JWT_SECRET)
        ctx.state.user = user
    } catch (err) {
        switch (err.name) {
            case "TokenExpiredError":
                ctx.app.emit('error', tokenExpiredError, ctx)
                break
            case "JsonWebTokenError":
                ctx.app.emit('error', jsonWebTokenError, ctx)
                break
        }
    }
    await next()
}

const hadAdminPermission = async (ctx, next) => {
    const is_admin = ctx.state.user.is_admin
    if (!is_admin) {
        return ctx.app.emit('error', hasNotAdminPermission, ctx)
    }
    await next()
}

module.exports = {
    auth,
    hadAdminPermission
}
